﻿using AutoMapper;
using B.S.AuthCenter.Api.Write.Application.Command.Menu;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Menu
{
    public class AddMenuHandler : IRequestHandler<AddMenuCommand, ApiResult<int>>
    {
        IBaseRepository<MenuManageModel> menuRepo;
        IMapper mapper;

        public AddMenuHandler(IBaseRepository<MenuManageModel> menuRepo, IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var menu=menuRepo.GetAll().Where(c=>c.Pid==request.Pid && c.MenuName == request.MenuName && !c.IsDeleted).Count();
            if (menu>0)
            {
               
                    res.Msg = "同一级菜单下名称不能重复";
                    res.Code=ApiEnum.Fail;
                    return Task.FromResult(res);
                
            }
            var model=mapper.Map<MenuManageModel>(request);
            model.Creator = request.Creator;
            model.CreatorDate=DateTime.Now;
            int a = menuRepo.Add(model).Result;
            if(a>0)
            {
                res.Msg = "添加菜单成功";
                res.Code = ApiEnum.Success;
                res.Datas = a;

            }
            else
            {
                res.Msg = "添加菜单失败";
                res.Code = ApiEnum.Fail;
                res.Datas = a;
            }
            return Task.FromResult(res);
        }
    }
}
